import React from 'react';
import { Row, Col, Card, Statistic, Typography, Space, Progress, Button, List, Tag } from 'antd';
import {
  WalletOutlined,
  BankOutlined,
  TrophyOutlined,
  DollarOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  EyeOutlined,
  ShareAltOutlined
} from '@ant-design/icons';

import { useAuth } from '../contexts/AuthContext';
import { useWallet } from '../contexts/WalletContext';
import { useQuery } from 'react-query';

const { Title, Text } = Typography;

const Dashboard = () => {
  const { apiCall } = useAuth();
  const { account } = useWallet();

  // Fetch dashboard data
  const { data: dashboardData, isLoading } = useQuery(
    'dashboard',
    () => apiCall('GET', '/users/dashboard'),
    {
      refetchInterval: 30000, // Refresh every 30 seconds
    }
  );

  const formatAddress = (address) => {
    if (!address) return '';
    return `${address.slice(0, 6)}...${address.slice(-4)}`;
  };

  const formatNumber = (num, decimals = 2) => {
    if (!num) return '0';
    return parseFloat(num).toFixed(decimals);
  };

  const StatCard = ({ title, value, icon, color, prefix, suffix, trend }) => (
    <Card className="h-full">
      <Statistic
        title={
          <Space>
            {icon}
            <Text>{title}</Text>
          </Space>
        }
        value={value}
        prefix={prefix}
        suffix={suffix}
        valueStyle={{ color }}
        precision={2}
      />
      {trend && (
        <div className="mt-2">
          <Tag color={trend > 0 ? 'green' : 'red'}>
            {trend > 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
            {Math.abs(trend)}%
          </Tag>
        </div>
      )}
    </Card>
  );

  if (isLoading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <Text>Loading dashboard...</Text>
        </div>
      </div>
    );
  }

  const user = dashboardData?.user || {};
  const recentTransactions = dashboardData?.recentTransactions || [];
  const staking = dashboardData?.staking || {};
  const referrals = dashboardData?.referrals || {};

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <Title level={2} className="text-gray-900 mb-2">
            Welcome back!
          </Title>
          <Text className="text-gray-600">
            {formatAddress(account)} • Referral Code: {user.referral_code}
          </Text>
        </div>

        {/* Stats Grid */}
        <Row gutter={[16, 16]} className="mb-8">
          <Col xs={24} sm={12} lg={6}>
            <StatCard
              title="Available Balance"
              value={formatNumber(user.available_balance)}
              icon={<WalletOutlined />}
              color="#1890ff"
              suffix="GOD"
            />
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <StatCard
              title="Staked Amount"
              value={formatNumber(user.staked_balance)}
              icon={<BankOutlined />}
              color="#52c41a"
              suffix="GOD"
            />
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <StatCard
              title="Total Earned"
              value={formatNumber(user.total_earned)}
              icon={<TrophyOutlined />}
              color="#faad14"
              suffix="GOD"
            />
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <StatCard
              title="Today's Interest"
              value={formatNumber(user.today_interest)}
              icon={<DollarOutlined />}
              color="#722ed1"
              suffix="GOD"
            />
          </Col>
        </Row>

        {/* Main Content */}
        <Row gutter={[16, 16]}>
          {/* Quick Actions */}
          <Col xs={24} lg={8}>
            <Card title="Quick Actions" className="h-full">
              <Space direction="vertical" className="w-full">
                <Button
                  type="primary"
                  size="large"
                  block
                  icon={<ArrowUpOutlined />}
                  href="/staking"
                >
                  Stake Tokens
                </Button>
                <Button
                  size="large"
                  block
                  icon={<ArrowDownOutlined />}
                  href="/staking"
                >
                  Unstake Tokens
                </Button>
                <Button
                  size="large"
                  block
                  icon={<ShareAltOutlined />}
                  href="/referrals"
                >
                  Share Referral Link
                </Button>
                <Button
                  size="large"
                  block
                  icon={<EyeOutlined />}
                  href="/transactions"
                >
                  View Transactions
                </Button>
              </Space>
            </Card>
          </Col>

          {/* Staking Overview */}
          <Col xs={24} lg={8}>
            <Card title="Staking Overview" className="h-full">
              <div className="space-y-4">
                <div>
                  <div className="flex justify-between mb-2">
                    <Text>Active Stakes</Text>
                    <Text strong>{staking.active_stakes || 0}</Text>
                  </div>
                  <Progress
                    percent={Math.min((staking.total_staked || 0) / 10000 * 100, 100)}
                    showInfo={false}
                    strokeColor="#52c41a"
                  />
                </div>

                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Text className="text-gray-600">Total Staked</Text>
                    <Text strong>{formatNumber(staking.total_staked)} GOD</Text>
                  </div>
                  <div className="flex justify-between">
                    <Text className="text-gray-600">First Stake Date</Text>
                    <Text>
                      {staking.first_stake_date
                        ? new Date(staking.first_stake_date).toLocaleDateString()
                        : 'No stakes yet'}
                    </Text>
                  </div>
                  <div className="flex justify-between">
                    <Text className="text-gray-600">Daily Rate</Text>
                    <Text strong className="text-green-600">1%</Text>
                  </div>
                </div>
              </div>
            </Card>
          </Col>

          {/* Referral Stats */}
          <Col xs={24} lg={8}>
            <Card title="Referral Stats" className="h-full">
              <div className="space-y-4">
                <Statistic
                  title="Total Referrals"
                  value={referrals.total_referrals || 0}
                  prefix={<ShareAltOutlined />}
                />
                <Statistic
                  title="Referral Rewards"
                  value={formatNumber(referrals.total_referral_rewards)}
                  prefix={<TrophyOutlined />}
                  suffix="GOD"
                  precision={2}
                />

                <div className="pt-4 border-t">
                  <Text className="text-gray-600 text-sm">
                    Your referral code earns you 10% rewards from your direct referrals' deposits.
                  </Text>
                </div>
              </div>
            </Card>
          </Col>
        </Row>

        {/* Recent Transactions */}
        <Row gutter={[16, 16]} className="mt-8">
          <Col xs={24}>
            <Card
              title="Recent Transactions"
              extra={
                <Button type="link" href="/transactions">
                  View All
                </Button>
              }
            >
              {recentTransactions.length > 0 ? (
                <List
                  dataSource={recentTransactions}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        title={
                          <Space>
                            <Tag color={
                              item.transaction_type === 'deposit' ? 'green' :
                              item.transaction_type === 'withdrawal' ? 'red' :
                              item.transaction_type === 'stake' ? 'blue' :
                              item.transaction_type === 'unstake' ? 'orange' :
                              'purple'
                            }>
                              {item.transaction_type.toUpperCase()}
                            </Tag>
                            <Text>{formatNumber(item.amount)} GOD</Text>
                          </Space>
                        }
                        description={
                          <Text type="secondary">
                            {new Date(item.created_at).toLocaleString()} •
                            Status: <Tag color={item.status === 'confirmed' ? 'green' : 'orange'}>
                              {item.status}
                            </Tag>
                          </Text>
                        }
                      />
                    </List.Item>
                  )}
                />
              ) : (
                <div className="text-center py-8">
                  <Text type="secondary">No transactions yet</Text>
                </div>
              )}
            </Card>
          </Col>
        </Row>
      </div>
    </div>
  );
};

export default Dashboard;